import { NotifyPlugin } from 'tdesign-vue-next'
import { useUserStore } from '@/stores'
import { router } from '@/router'
import { fetchRequest } from './fetch-index'

const env = import.meta.env
const BASE_URL = env.VITE_APP_BASE_API

export interface FetchResponse<T> {
  fail: number
  message: string
  data: T
}

export interface FetchRequestInit extends RequestInit {
  data?: { [key: string]: any } | any[]
  params?: { [key: string]: any }
}

export async function request<T>(
  url: string,
  options: FetchRequestInit
): Promise<FetchResponse<T>> {
  const userStore = useUserStore()
  const { data, params } = options
  const _options = {
    method: options.method ?? 'GET',
    ...options,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${userStore.token}`,
      ...options.headers
    }
  }

  // if (userStore.token) {
  //   _options.headers['Authorization'] = `Bearer ${userStore.token}`
  // }

  if (data) {
    _options.body = JSON.stringify(data)
  } else if (params) {
    url = `${url}?${new URLSearchParams(params).toString()}`
  }
  return fetchRequest(url, _options)
}

const fetch = {
  post: <T>(url: string, opts?: FetchRequestInit) => request<T>(url, { ...opts, method: 'post' }),
  get: <T>(url: string, opts?: FetchRequestInit) => request<T>(url, { ...opts, method: 'get' }),
  put: <T>(url: string, opts?: FetchRequestInit) => request<T>(url, { ...opts, method: 'put' }),
  delete: <T>(url: string, opts?: FetchRequestInit) =>
    request<T>(url, { ...opts, method: 'delete' })
}

export { fetch }
